<template>
  <div class="sentence-study">
    <el-skeleton :rows="5" animated v-if="loading" />
    <el-alert v-else-if="error" :title="error" type="error" show-icon :closable="false" />
    <div v-else>
      <MyHeaderInLesson :lesson="lesson" :moduleName="'句子学习'" />

      <AudioControls
        :current-index="currentSentenceIndex"
        :total-items="lesson.content.length"
        :is-playing="isPlaying"
        @previous="playPrevious"
        @toggle-playback="togglePlayback"
        @next="playNext"
        @speed-change="changeSpeed"
      />

      <!-- 句子选择下拉框 -->
      <div class="sentence-selector">
        <el-select v-model="currentSentenceIndex" placeholder="请选择句子" style="width: 100%" class="mosaic-text">
          <el-option
            v-for="(sentence, index) in lesson.content"
            :key="index"
            :label="`${index + 1}. ${sentence.english}`"
            :value="index"
          >
            <div class="sentence-option">
              <span class="sentence-number">{{ index + 1 }}.</span>
              <span class="sentence-text">{{ sentence.english }}</span>
            </div>
          </el-option>
        </el-select>
      </div>

      <!-- 句子学习控制选项 -->
      <div class="sentence-study-options">
        <el-button @click="setStartPoint" :disabled="!lesson || lesson.content.length === 0" class="control-button">
          开始点
        </el-button>
        <el-button @click="setEndPoint" :disabled="!lesson || lesson.content.length === 0" class="control-button">
          结束点
        </el-button>
        <el-button
          @click="recordSentence"
          :disabled="!lesson || lesson.content.length === 0"
          class="control-button primary"
        >
          录音
        </el-button>
        <el-button @click="playRecorded" :disabled="!hasRecording(currentSentenceIndex)" class="control-button">
          您的朗读
        </el-button>
      </div>

      <!-- 当前句子显示 -->
      <div class="current-sentence-display" v-if="lesson && lesson.content.length > 0">
        <div class="sentence-item english">
          <p>{{ currentSentence.english }}</p>
        </div>
        <div class="sentence-item chinese">
          <p>{{ currentSentence.chinese }}</p>
        </div>
      </div>

      <!-- 录音状态显示 -->
      <div class="recording-status" v-if="isRecording">
        <el-alert title="录音中..." type="warning" :closable="false" center />
      </div>

      <!-- 已录制音频列表 -->
      <div class="recorded-audio-list" v-if="Object.keys(recordedAudios).length > 0">
        <h3>已录制的句子</h3>
        <el-table :data="recordedAudioList" style="width: 100%">
          <el-table-column prop="index" label="#" width="60" />
          <el-table-column prop="sentence" label="句子" />
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-icon @click="playRecorded(scope.row.index)" :size="24">
                <VideoPlay />
              </el-icon>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import AudioControls from '../components/text-study/AudioControls.vue'
import { ElSkeleton, ElAlert, ElPageHeader, ElButton, ElTable, ElTableColumn, ElIcon } from 'element-plus'
import { VideoPlay } from '@element-plus/icons-vue'
import { lessonLoader } from '../mixins/lessonLoader.js'
import MyHeaderInLesson from '../components/layout/MyHeaderInLesson.vue'
import KeyboardAudio from '../utils/keyboardAudio.js'

export default {
  name: 'SentenceStudy',
  components: {
    AudioControls,
    ElSkeleton,
    ElAlert,
    ElPageHeader,
    ElButton,
    ElTable,
    ElTableColumn,
    VideoPlay,
    ElIcon,
    MyHeaderInLesson
  },
  mixins: [lessonLoader],
  data() {
    return {
      recordedAudios: {}, // 修改为对象，存储所有录制的音频
      mediaRecorder: null,
      recordingChunks: [],
      currentSentenceIndex: 0,
      isPlaying: false,
      isRecording: false,
      sentenceStartTime: 0,
      sentenceEndTime: 0,
      userStartTime: 0,
      userEndTime: 0
    }
  },
  computed: {
    currentSentence() {
      if (!this.lesson || !this.lesson.content || this.lesson.content.length === 0) {
        return { english: '', chinese: '' }
      }
      return this.lesson.content[this.currentSentenceIndex] || { english: '', chinese: '' }
    },
    // 将recordedAudios转换为表格数据
    recordedAudioList() {
      return Object.keys(this.recordedAudios).map((index) => ({
        index: parseInt(index) + 1,
        sentence: this.lesson.content[index].english
      }))
    }
  },
  async mounted() {
    KeyboardAudio.register('Enter', this.togglePlayback)
    // 注册空格键
    KeyboardAudio.register(' ', this.togglePlayback)
    KeyboardAudio.register('ArrowLeft', this.playPrevious)
    KeyboardAudio.register('ArrowRight', this.playNext)
    const lessonId = this.$route.params.id
    await this.loadLesson(lessonId)

    // Check for sentence_id parameter and set current sentence index
    const sentenceId = this.$route.query.sentence_id
    if (sentenceId && !isNaN(sentenceId) && sentenceId > 0) {
      // Convert to 0-based index
      const index = parseInt(sentenceId) - 1
      // Make sure it's within bounds
      if (index < this.lesson.content.length) {
        this.currentSentenceIndex = index
      }
    }
  },
  beforeUnmount() {
    KeyboardAudio.destroy()
    if (this.audio) {
      this.audio.pause()
      this.audio = null
    }

    // 清理所有录制的音频资源
    Object.values(this.recordedAudios).forEach((audio) => {
      if (audio) {
        audio.pause()
      }
    })
  },
  methods: {
    playPrevious() {
      if (this.currentSentenceIndex > 0) {
        this.currentSentenceIndex--
        // 切换句子时清空自定义的开始点和结束点
        this.userStartTime = 0
        this.userEndTime = 0
        this.playCurrentSentence()
      }
    },

    togglePlayback() {
      if (this.isPlaying) {
        this.pauseAudio()
      } else {
        this.playCurrentSentence()
      }
    },

    playNext() {
      if (this.currentSentenceIndex < this.lesson.content.length - 1) {
        this.currentSentenceIndex++
        // 切换句子时清空自定义的开始点和结束点
        this.userStartTime = 0
        this.userEndTime = 0
        this.playCurrentSentence()
      }
    },

    playCurrentSentence() {
      if (!this.audio || this.lesson.content.length === 0) return

      const sentence = this.lesson.content[this.currentSentenceIndex]
      // 如果用户设置了开始/结束点，则使用用户设置的点
      const startTime = this.userStartTime || sentence.startTime
      const endTime = this.userEndTime || sentence.endTime

      if (startTime !== undefined && endTime !== undefined) {
        this.audio.currentTime = startTime
        this.sentenceEndTime = endTime
        this.audio.play()
        this.isPlaying = true
      }
    },

    pauseAudio() {
      if (this.audio) {
        this.audio.pause()
      }
      this.isPlaying = false
    },

    onAudioTimeUpdate() {
      // 检查是否到达句子结束时间
      if (this.isPlaying && this.audio && this.audio.currentTime >= this.sentenceEndTime) {
        this.audio.pause()
        this.isPlaying = false
      }
    },

    onAudioEnded() {
      this.isPlaying = false
    },

    changeSpeed(speed) {
      if (this.audio) {
        this.audio.playbackRate = speed
      }
    },

    setStartPoint() {
      if (!this.audio || this.lesson.content.length === 0) return

      const sentence = this.lesson.content[this.currentSentenceIndex]
      this.userStartTime = this.audio.currentTime
      // 确保开始点不晚于结束点
      if (this.userStartTime >= (this.userEndTime || sentence.endTime)) {
        this.userEndTime = 0
      }
    },

    setEndPoint() {
      if (!this.audio || this.lesson.content.length === 0) return

      const sentence = this.lesson.content[this.currentSentenceIndex]
      this.userEndTime = this.audio.currentTime
      // 确保结束点不早于开始点
      if (this.userEndTime <= (this.userStartTime || sentence.startTime)) {
        this.userStartTime = 0
      }
    },

    async recordSentence() {
      if (this.isRecording) {
        this.stopRecording()
        return
      }

      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
        this.mediaRecorder = new MediaRecorder(stream)
        this.recordingChunks = []

        this.mediaRecorder.ondataavailable = (event) => {
          if (event.data.size > 0) {
            this.recordingChunks.push(event.data)
          }
        }

        this.mediaRecorder.onstop = () => {
          const audioBlob = new Blob(this.recordingChunks, { type: 'audio/webm' })
          const audio = new Audio(URL.createObjectURL(audioBlob))
          // 使用当前句子索引作为键存储录音
          this.recordedAudios[this.currentSentenceIndex] = audio
          stream.getTracks().forEach((track) => track.stop())
        }

        this.mediaRecorder.start()
        this.isRecording = true
        this.playCurrentSentence() // 开始播放原音的同时开始录音
      } catch (err) {
        console.error('录音失败:', err)
        this.error = '录音功能不可用，请检查麦克风权限'
      }
    },

    stopRecording() {
      if (this.mediaRecorder && this.isRecording) {
        this.mediaRecorder.stop()
        this.isRecording = false
        this.pauseAudio() // 停止播放原音
      }
    },

    playRecorded(index) {
      // 如果没有传入index参数，则使用当前句子索引
      const targetIndex = index !== undefined ? index - 1 : this.currentSentenceIndex
      const recordedAudio = this.recordedAudios[targetIndex]
      if (recordedAudio) {
        recordedAudio.play()
      }
    },

    // 检查特定句子是否有录音
    hasRecording(index) {
      return !!this.recordedAudios[index]
    }
  }
}
</script>

<style scoped lang="scss">
@use '../assets/styles/sentenceStudy.scss';
</style>